package com.yzt.loginmodule.report;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yzt.zhuju.arouter.RouterAccount;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.sysConfig.ReportItemBean;
import com.yzt.zhuju.network.entity.sysConfig.ReportPhotoBean;
import com.yzt.zhuju.photoview.PhotoViewManager;
import com.yzt.zhuju.utils.AppDialogUtil;
import com.yzt.zhuju.utils.DefaultCropFileEngine;
import com.yzt.zhuju.utils.GlideImageEngine;
import com.yzt.zhuju.utils.ImageUpLoadUtils;
import com.yzt.zhuju.utils.McImageCompressEngine;
import com.yzt.zhuju.utils.ViewUtil;
import com.yzt.loginmodule.R;
import com.yzt.loginmodule.report.adapter.ReportItemAdapter;
import com.yzt.loginmodule.report.adapter.ReportPhotoAdapter;
import com.yzt.p_base.AppUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.zhuju.widget.tuiview.TUITextView;

import java.util.ArrayList;
import java.util.List;

/**
 * author : bob
 * date   : 2022/12/8
 * desc   :举报
 */
@SuppressLint("SetTextI18n")
@Route(path = RouterAccount.ACTIVITY_REPORT)
public class ReportActivity extends BaseActivity {

    private int step = 1;

    public final static int SPANCOUNT = 4;

    private ReportItemAdapter mReportItemAdapter;

    private List<ReportItemBean> mItemList;

    private final List<ReportPhotoBean> mPhotoArray = new ArrayList<>();

    private EditText mReportEt;

    private TextView mEditNumTv;

    private ReportPhotoAdapter mReportPhotoAdapter;

    @Autowired
    public String mUserId;

    @Autowired
    public String dynamicId;

    private LinearLayout ll_pic_container;

    private RecyclerView mReportItemRv;

    @Override
    public int getLayoutId() {
        return R.layout.activity_report;
    }

    @Override
    public void installViews() {
        mTitleBar.setTitle(R.string.str_report);

        ll_pic_container = findViewById(R.id.ll_pic_container);
        mReportItemRv = findViewById(R.id.report_item_rv);

        mReportEt = findViewById(R.id.report_et);
        mEditNumTv = findViewById(R.id.edit_num_tv);
        ViewUtil.addTextChangedListener(mReportEt, text -> mEditNumTv.setText(text.length() + "/200"));

        findViewById(R.id.commit_tv).setOnClickListener(this);

        // 加载列表
        loadRecycleView();

        // 初始化数据
        initData();
    }

    /**
     * 加载列表信息
     */
    private void loadRecycleView() {
        mReportItemRv.setLayoutManager(new LinearLayoutManager(mActivity));
        mReportItemAdapter = new ReportItemAdapter();
        mReportItemRv.setAdapter(mReportItemAdapter);
        mReportItemAdapter.setOnItemClickListener((adapter, view, position) -> {
            for (ReportItemBean bean : mReportItemAdapter.getData()) {
                bean.setSelect(false);
            }
            mItemList.get(position).setSelect(true);
            mReportItemAdapter.notifyDataSetChanged();
        });

        RecyclerView mPhotoRv = findViewById(R.id.photo_rv);
        mPhotoRv.setLayoutManager(new GridLayoutManager(mActivity, SPANCOUNT));
        mReportPhotoAdapter = new ReportPhotoAdapter();
        mPhotoRv.setAdapter(mReportPhotoAdapter);
        mReportPhotoAdapter.addData(new ReportPhotoBean(-1, "", ""));
        mReportPhotoAdapter.addChildClickViewIds(R.id.delete_iv);
        mReportPhotoAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.delete_iv) {
                AppDialogUtil.showNoTitleDialog(mActivity, mActivity.getString(R.string.str_delete_photo), mActivity.getString(R.string.cancel), mActivity.getString(R.string.delete), new AppDialogUtil.DialogClickInterface() {
                    @Override
                    public void onCancelClick() {

                    }

                    @Override
                    public void onSureClick() {
                        mReportPhotoAdapter.remove(position);
                        delPhotoCal();
                    }
                });
            }
        });

        mReportPhotoAdapter.setOnItemClickListener((adapter, view, position) -> {
            ReportPhotoBean itemLayoutEntry = (ReportPhotoBean) adapter.getData().get(position);
            if (itemLayoutEntry.getStatus() == -1) {//拍照
                if (mPhotoArray.size() >= 6) {
                    return;
                }
                selectImage();
            } else {  //查看
                List<ReportPhotoBean> dataList = (List<ReportPhotoBean>) adapter.getData();
                List<String> list = new ArrayList<>();
                for (ReportPhotoBean entry : dataList) {
                    if (!TextUtils.isEmpty(entry.getPathUrl())) {
                        list.add(entry.getPathUrl());
                    }
                }
                PhotoViewManager.getInstance(AppUtils.getApp()).showPhotoView(view, list, position);
            }
        });
    }

    /**
     * 选择图片
     */
    private void selectImage() {
        PictureSelector.create(mActivity).openGallery(SelectMimeType.ofImage()).setImageEngine(GlideImageEngine.Companion.getInstance()).setCompressEngine(McImageCompressEngine.Companion.getInstance()).setCropEngine(new DefaultCropFileEngine()).setMaxSelectNum(6 - mPhotoArray.size()).isDirectReturnSingle(true).isDisplayCamera(false).isOpenClickSound(false).isFastSlidingSelect(true).isPreviewFullScreenMode(true).isPreviewZoomEffect(true).isPreviewImage(true).isMaxSelectEnabledMask(true).isGif(false).forResult(PictureConfig.CHOOSE_REQUEST);

    }

    public void initData() {
        mItemList = new ArrayList<>();
        mItemList.add(new ReportItemBean("违法犯罪（涉证、暴恐和黄赌毒等）", false));
        mItemList.add(new ReportItemBean("令人不适（低俗骚扰、暴力血腥等）", false));
        mItemList.add(new ReportItemBean("其他内容（辱骂、人身攻击或广告等）", false));
        mReportItemAdapter.setList(mItemList);
    }

    @Override
    protected void onClick(int clickId) {
        super.onClick(clickId);
        if (clickId == R.id.commit_tv) {

            if (step == 1) {

                boolean check = false;

                for (ReportItemBean bean : mReportItemAdapter.getData()) {
                    if (bean.isSelect()) {
                        check = true;
                        break;
                    }
                }

                if (!check) {
                    showToast("请选择举报类型");
                    return;
                }

                step = 2;
                ((TUITextView) findViewById(R.id.commit_tv)).setText("提交");
                ll_pic_container.setVisibility(View.VISIBLE);
                mReportItemRv.setVisibility(View.GONE);
            } else {

                List<String> urlList1 = new ArrayList<>();

                if (!mPhotoArray.isEmpty()) {
                    // 发布图文动态
                    for (ReportPhotoBean bean : mPhotoArray) {

                        String time = System.currentTimeMillis() + ".png";

                        ImageUpLoadUtils.getInstance().asyncUpLoad(time, bean.getPathUrl(), new ImageUpLoadUtils.OnAsyncUpLoadListener() {

                            @Override
                            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                            }

                            @Override
                            public void onSuccess(PutObjectRequest request, PutObjectResult result, String directory) {
                                urlList1.add(directory + request.getObjectKey());
                                if (urlList1.size() == mPhotoArray.size()) {
                                    addReport(urlList1);
                                }
                            }

                            @Override
                            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                                showToast("上传失败");
                                closeProgress();
                            }
                        });
                    }
                } else {
                    addReport(urlList1);
                }
            }
        }
    }

    private void addReport(List<String> urlList1) {

        StringBuilder sb = new StringBuilder();
        for (ReportItemBean entry : mItemList) {
            if (entry.isSelect()) {
                sb.append(entry.getContent());
                sb.append(",");
            }
        }

        String reportContent = mReportEt.getText().toString().trim();
        if (TextUtils.isEmpty(reportContent)) {
            ToastUtil.showMessage(R.string.report_tosat_input);
            return;
        }

        int position = 0;

        for (int i = 1; i < mReportItemAdapter.getData().size(); i++) {

            if (mReportItemAdapter.getData().get(i).isSelect()) {
                position = i;
            }
        }

        showMProgress();

        BizLayer.getInstance().getAccountModule().relationInform(dynamicId, mUserId, position, reportContent, urlList1, new AresSubscriber<Object>() {
            @Override
            protected void onSuccess(Object response) {
                ToastUtil.showMessage(R.string.report_success);
                finish();
            }

            @Override
            protected void onFinallyEnd() {
                super.onFinallyEnd();
                closeProgress();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {
                List<ReportPhotoBean> photoList = mReportPhotoAdapter.getData();
                ArrayList<LocalMedia> result = PictureSelector.obtainSelectorList(data);
                for (LocalMedia bean : result) {
                    String picturePath = bean.getRealPath();
                    ReportPhotoBean photo = new ReportPhotoBean(1, picturePath, picturePath);
                    photoList.add(photo);
                }

                mReportPhotoAdapter.notifyDataSetChanged();
            }
            delPhotoCal();
        }
    }

    public void delPhotoCal() {
        mPhotoArray.clear();
        if (mReportPhotoAdapter.getData().size() > 6) {
            List<ReportPhotoBean> photoList = new ArrayList<>();
            for (ReportPhotoBean file : mReportPhotoAdapter.getData()) {
                if (file.getStatus() != -1) {
                    photoList.add(file);
                    mPhotoArray.add(new ReportPhotoBean(1, file.getPathUrl(), file.getPathUrl()));
                }
            }
            if (photoList.size() == 6) {
                mReportPhotoAdapter.getData().clear();
                mReportPhotoAdapter.addData(photoList);
            } else {
                photoList.add(0, new ReportPhotoBean(-1, "", ""));
            }
        } else {
            for (ReportPhotoBean file : mReportPhotoAdapter.getData()) {
                if (file.getStatus() != -1) {
                    mPhotoArray.add(new ReportPhotoBean(1, file.getPathUrl(), file.getPathUrl()));
                }
            }
        }
    }
}
